package com.sxj.corejava.code13_JDBC;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class Test14_druid {

    public static void main(String[] args) throws SQLException {
        test02();
    }

    public static void test01() throws SQLException {
        DruidDataSource ds = new DruidDataSource();

        // 设置数据库连接信息
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8");
        ds.setUsername("root");
        ds.setPassword("root");

        // 配置连接池信息
        ds.setInitialSize(1);
        ds.setMaxActive(2);
        ds.setMaxIdle(1);
        ds.setMinIdle(1);
        ds.setMaxWait(3000);

        // 测试
        Connection conn = ds.getConnection();
        System.out.println(conn);
        conn.close();

        Connection conn2 = ds.getConnection();
        System.out.println(conn2);

        Connection conn3 = ds.getConnection();
        System.out.println(conn3);
    }

    public static void test02() throws SQLException {
        Properties p = new Properties();
        try {
            p.load(Test14_druid.class.getClassLoader().getResourceAsStream("dataSource.properties"));

            DataSource ds = DruidDataSourceFactory.createDataSource(p);
            Connection conn = ds.getConnection();
            System.out.println(conn);
            Connection conn2 = ds.getConnection();
            System.out.println(conn2);
            Connection conn3 = ds.getConnection();
            System.out.println(conn3);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
